package com.xzx.study;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;

public class AsyncTaskActivity extends AppCompatActivity {

    private static final String TAG = AsyncTaskActivity.class.getSimpleName();

    private Button async_task_btn;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);
        async_task_btn = findViewById(R.id.async_task_btn);
        async_task_btn.setOnClickListener(v -> {
            MyAsyncTask myAsyncTask = new MyAsyncTask();
            myAsyncTask.execute();
        });
    }

    class MyAsyncTask extends AsyncTask<Integer, Integer, Void> {
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "=====onPreExecute===主线程执行");
            progressDialog = new ProgressDialog(AsyncTaskActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Integer... params) {
            Log.i(TAG, "=====doInBackground===分线程执行");
            progressDialog.setMax(100);
            for (int i =0; i <= 20; i++) {
                SystemClock.sleep(1000);
                publishProgress(i * 5);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Log.i(TAG, "=====onPostExecute===主线程执行");
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i(TAG, "=====onProgressUpdate===主线程执行");
            progressDialog.setProgress(values[0]);
        }
    }
}
